﻿using MediatR;
using Traceability.Commont.Domains.ScratchTheFat;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.WhiteStripWeighingHtmlGroup;
using Traceability.Commont.Infrastructures.Interfaces;

namespace U.Enterprise.Api.Applications.SalesWeighingEXE
{
    public class SalesGroupHander : IRequestHandler<SalesGroupCommand, Resqults<SaleGroupDTO>>
    {
        private readonly IBateRepository<SalesWeighing> sales;

        public SalesGroupHander(IBateRepository<SalesWeighing> sales)
        {
            this.sales = sales;
        }

        public async Task<Resqults<SaleGroupDTO>> Handle(SalesGroupCommand request, CancellationToken cancellationToken)
        {
            try
            {
                int years = DateTime.Now.Year;
                int months = DateTime.Now.Month;
                if (request.Date != null)
                {
                    years = request.Date.Value.Year;
                    months = request.Date.Value.Month;
                }
                Resqults<SaleGroupDTO> res = new Resqults<SaleGroupDTO>();
                var list = (from a in sales.GetAll()
                           where (a.WeigheTime.Year == years && a.WeigheTime.Month == months)
                           group new { a } by new { a.WeigheTime.Day } into c
                           select new SaleGroupDTO()
                           {
                               WeightNum = c.Sum(x => x.a.WeightNum),
                               WeightSum = c.Sum(x => x.a.WeightNum * x.a.NetWeight)
                           }).ToList();
                res.Date = list;
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
